package com.gewu.pm.ui.dialog;

import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_DRAGGING;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppAdapter;
import com.google.android.material.tabs.TabLayout;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择提交人对话框（支持动态配置Tab）
 * 根据 type 参数显示不同的 Tab 组合：
 * - type=1: 配送商、业务员、部门（电汇收款）
 * - type=2: 终端、业务员、部门（销售订单）
 *   type=101 = 只显示配送商  102 = 只显示终端  103 = 只显示业务员  104 = 只显示部门
 */
public final class SelectSubmitterDialog {

    // ==================== 策略模式：数据提供者接口 ====================

    /**
     * 提交人数据提供者接口（策略模式）
     * 每个 Tab 页面实现此接口，提供数据加载、搜索等功能
     */
    public interface ISubmitterProvider {
        /**
         * 加载数据
         */
        void loadData();

        /**
         * 搜索/过滤数据
         * @param keyword 搜索关键词
         */
        void filter(String keyword);

        /**
         * 创建适配器
         */
        RecyclerView.Adapter<?> createAdapter(Context context, Builder builder);
    }

    /**
     * Tab 配置项
     */
    public static class TabItem {
        private final String tabName;
        private final ISubmitterProvider provider;

        public TabItem(String tabName, ISubmitterProvider provider) {
            this.tabName = tabName;
            this.provider = provider;
        }

        public String getTabName() {
            return tabName;
        }

        public ISubmitterProvider getProvider() {
            return provider;
        }
    }

    /**
     * Tab 配置工厂（根据 type 返回不同的 Tab 配置）
     */
    public static class TabConfig {
        /**
         * 根据 type 获取 Tab 配置
         * 
         * Type 编码规范：
         * - 1-100: 多Tab模式
         *   - 1 = 配送商、业务员、部门（电汇收款）
         *   - 2 = 终端、业务员、部门（销售订单）
         *   - 0 或其他 = 终端、业务员、部门（默认）
         * 
         * - 101-200: 单Tab模式（只显示一个列表，隐藏Tab栏）
         *   - 101 = 只显示配送商
         *   - 102 = 只显示终端
         *   - 103 = 只显示业务员
         *   - 104 = 只显示部门
         * 
         * @param type 类型编码
         */
        public static List<TabItem> getTabsByType(int type) {
            List<TabItem> tabs = new ArrayList<>();
            
            // ========== 多Tab模式（1-100） ==========
            if (type == 1) {
                // 电汇收款：配送商、业务员、部门
                tabs.add(new TabItem("配送商", new DistributorProvider()));
                tabs.add(new TabItem("业务员", new EmployeeProvider()));
                tabs.add(new TabItem("部门", new DepartmentProvider()));
            } else if (type == 2) {
                // 销售订单：终端、业务员、部门
                tabs.add(new TabItem("终端", new TerminalProvider()));
                tabs.add(new TabItem("业务员", new EmployeeProvider()));
                tabs.add(new TabItem("部门", new DepartmentProvider()));
            } else if (type >= 1 && type <= 100) {
                // 其他多Tab模式（默认）：终端、业务员、部门
                tabs.add(new TabItem("终端", new TerminalProvider()));
                tabs.add(new TabItem("业务员", new EmployeeProvider()));
                tabs.add(new TabItem("部门", new DepartmentProvider()));
            }
            
            // ========== 单Tab模式（101-200） ==========
            else if (type == 101) {
                // 只显示配送商
                tabs.add(new TabItem("配送商", new DistributorProvider()));
            } else if (type == 102) {
                // 只显示终端
                tabs.add(new TabItem("终端", new TerminalProvider()));
            } else if (type == 103) {
                // 只显示业务员
                tabs.add(new TabItem("业务员", new EmployeeProvider()));
            } else if (type == 104) {
                // 只显示部门
                tabs.add(new TabItem("部门", new DepartmentProvider()));
            }
            
            // ========== 默认模式 ==========
            else {
                // 默认：终端、业务员、部门（兼容旧代码）
                tabs.add(new TabItem("终端", new TerminalProvider()));
                tabs.add(new TabItem("业务员", new EmployeeProvider()));
                tabs.add(new TabItem("部门", new DepartmentProvider()));
            }
            
            return tabs;
        }
    }

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements TabLayout.OnTabSelectedListener,
            BaseDialog.OnShowListener, BaseDialog.OnDismissListener {

        private OnListener mListener;

        private final TextView mCancelView;
        private final TextView mTitleView;
        private final TextView mConfirmView;
        private final EditText mSearchEdit;
        private final TabLayout mTabLayout;
        private final ViewPager2 mViewPager;
        private final RecyclerViewPagerAdapter mPagerAdapter;
        private final ViewPager2.OnPageChangeCallback mCallback;

        /** 当前选中的提交人名称（单选模式） */
        private String mSelectedSubmitter = null;
        /** 当前选中的类型（Tab索引） */
        private int mSelectedType = -1;
        /** 当前选中的完整数据对象（单选模式） */
        private Object mSelectedData = null;
        /** 是否多选模式 */
        private boolean mMultiSelect = false;
        
        /** Tab 配置列表 */
        private List<TabItem> mTabItems;
        
        /** 搜索防抖 Handler（避免频繁搜索导致卡顿） */
        private final Handler mSearchHandler = new Handler(Looper.getMainLooper());
        private Runnable mSearchRunnable;
        private static final long SEARCH_DELAY = 300; // 300ms 防抖延迟

        /**
         * 构造函数（兼容旧代码，默认显示终端、业务员、部门）
         */
        public Builder(Context context) {
            this(context, 0); // 默认 type=0
        }

        /**
         * 构造函数（支持动态配置 Tab）
         * @param context 上下文
         * @param type 类型：1=电汇收款(配送商、业务员、部门), 2=销售订单(终端、业务员、部门)   101 = 只显示配送商  102 = 只显示终端  103 = 只显示业务员  104 = 只显示部门
         */
        public Builder(Context context, int type) {
            super(context);
            setContentView(R.layout.select_submitter_dialog);
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            // 设置高度为屏幕的 2/3
            setHeight(getResources().getDisplayMetrics().heightPixels * 2 / 3);

            mCancelView = findViewById(R.id.tv_submitter_cancel);
            mTitleView = findViewById(R.id.tv_submitter_title);
            mConfirmView = findViewById(R.id.tv_submitter_confirm);
            mSearchEdit = findViewById(R.id.et_submitter_search);
            mTabLayout = findViewById(R.id.tb_submitter_tab);
            mViewPager = findViewById(R.id.vp_submitter_pager);

            setOnClickListener(mCancelView, mConfirmView);

            // 根据 type 获取 Tab 配置
            mTabItems = TabConfig.getTabsByType(type);

            // 判断是单Tab模式还是多Tab模式
            if (mTabItems.size() == 1) {
                // ========== 单Tab模式：隐藏 TabLayout ==========
                mTabLayout.setVisibility(View.GONE);
                mTitleView.setText("选择" + mTabItems.get(0).getTabName());
            } else {
                // ========== 多Tab模式：显示 TabLayout ==========
                mTabLayout.setVisibility(View.VISIBLE);
                mTitleView.setText("选择提交人");
                
                // 动态添加 Tab
                for (TabItem tabItem : mTabItems) {
                    mTabLayout.addTab(mTabLayout.newTab().setText(tabItem.getTabName()));
                }
            }
            
            mTabLayout.addOnTabSelectedListener(this);

            // 设置 ViewPager
            mPagerAdapter = new RecyclerViewPagerAdapter(getContext(), this, mTabItems);
            mViewPager.setAdapter(mPagerAdapter);

            // ViewPager 滑动监听
            mCallback = new ViewPager2.OnPageChangeCallback() {
                private int mPreviousScrollState, mScrollState = SCROLL_STATE_IDLE;

                @Override
                public void onPageScrollStateChanged(int state) {
                    mPreviousScrollState = mScrollState;
                    mScrollState = state;
                    if (state == ViewPager2.SCROLL_STATE_IDLE && mTabLayout.getSelectedTabPosition() != mViewPager.getCurrentItem()) {
                        final boolean updateIndicator = mScrollState == SCROLL_STATE_IDLE || (mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
                        mTabLayout.selectTab(mTabLayout.getTabAt(mViewPager.getCurrentItem()), updateIndicator);
                    }
                }

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    final boolean updateText = mScrollState != SCROLL_STATE_SETTLING || mPreviousScrollState == SCROLL_STATE_DRAGGING;
                    final boolean updateIndicator = !(mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
                    mTabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator);
                }
            };

            // 设置搜索功能
            setupSearch();

            addOnShowListener(this);
            addOnDismissListener(this);
        }

        /**
         * 设置搜索功能（带防抖机制，避免频繁搜索导致卡顿）
         */
        private void setupSearch() {
            mSearchEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String keyword = s.toString().trim();
                    
                    // 移除之前的搜索任务（防抖）
                    if (mSearchRunnable != null) {
                        mSearchHandler.removeCallbacks(mSearchRunnable);
                    }
                    
                    // 延迟执行搜索（用户停止输入 300ms 后才执行）
                    mSearchRunnable = () -> {
                        int currentPage = mViewPager.getCurrentItem();
                        mPagerAdapter.filterData(currentPage, keyword);
                    };
                    
                    mSearchHandler.postDelayed(mSearchRunnable, SEARCH_DELAY);
                }
            });
        }

        /**
         * 选择提交人（单选模式）
         * @param type Tab索引
         * @param name 提交人名称
         * @param data 完整数据对象
         */
        void onSubmitterSelected(int type, String name, Object data) {
            mSelectedType = type;
            mSelectedSubmitter = name;
            mSelectedData = data;
        }
        
        /**
         * 获取是否多选模式
         */
        boolean isMultiSelect() {
            return mMultiSelect;
        }
        
        /**
         * 设置是否多选模式
         */
        public Builder setMultiSelect(boolean multiSelect) {
            mMultiSelect = multiSelect;
            return this;
        }

        /**
         * 设置监听器
         */
        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            int viewId = view.getId();
            if (viewId == R.id.tv_submitter_cancel) {
                // 取消
                dismiss();
                if (mListener != null) {
                    mListener.onCancel(getDialog());
                }
            } else if (viewId == R.id.tv_submitter_confirm) {
                // 确定
                if (mMultiSelect) {
                    // 多选模式：收集所有Tab中选中的项
                    String result = mPagerAdapter.collectAllSelectedItems();
                    
                    if (TextUtils.isEmpty(result)) {
                        // 如果没有选择，提示并返回
                        Toast.makeText(getContext(), "请先选择提交人", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    dismiss();
                    if (mListener != null) {
                        // 多选模式返回所有Tab的选中数据，type为当前Tab索引
                        int currentPage = mViewPager.getCurrentItem();
                        mListener.onSelected(getDialog(), result, currentPage, null);
                    }
                } else {
                    // 单选模式
                    if (TextUtils.isEmpty(mSelectedSubmitter)) {
                        // 如果没有选择，提示并返回
                        Toast.makeText(getContext(), "请先选择提交人", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    dismiss();
                    if (mListener != null) {
                        mListener.onSelected(getDialog(), mSelectedSubmitter, mSelectedType, mSelectedData);
                    }
                }
            }
        }

        /**
         * {@link TabLayout.OnTabSelectedListener}
         */
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (mViewPager.getCurrentItem() != tab.getPosition()) {
                mViewPager.setCurrentItem(tab.getPosition());
            }
            // 清空搜索框
            mSearchEdit.setText("");
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }

        /**
         * {@link BaseDialog.OnShowListener}
         */
        @Override
        public void onShow(BaseDialog dialog) {
            // 注册 ViewPager 滑动监听
            mViewPager.registerOnPageChangeCallback(mCallback);
        }

        /**
         * {@link BaseDialog.OnDismissListener}
         */
        @Override
        public void onDismiss(BaseDialog dialog) {
            // 反注册 ViewPager 滑动监听
            mViewPager.unregisterOnPageChangeCallback(mCallback);
            
            // 清理搜索 Handler，避免内存泄漏
            if (mSearchRunnable != null) {
                mSearchHandler.removeCallbacks(mSearchRunnable);
                mSearchRunnable = null;
            }
        }
    }

    /**
     * ViewPager 适配器（策略模式重构版）
     */
    private static final class RecyclerViewPagerAdapter extends AppAdapter<TabItem> {

        private final Builder mBuilder;
        private final List<RecyclerView.Adapter<?>> mAdapters;

        private RecyclerViewPagerAdapter(Context context, Builder builder, List<TabItem> tabItems) {
            super(context);
            mBuilder = builder;
            mAdapters = new ArrayList<>();

            // 根据 TabItem 配置动态创建适配器
            for (TabItem tabItem : tabItems) {
                ISubmitterProvider provider = tabItem.getProvider();
                provider.loadData(); // 加载数据
                RecyclerView.Adapter<?> adapter = provider.createAdapter(context, builder);
                mAdapters.add(adapter);
            }

            // 设置页面数据
            setData(tabItems);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder {

            private final RecyclerView mRecyclerView;

            ViewHolder() {
                super(new RecyclerView(getContext()));
                mRecyclerView = (RecyclerView) getItemView();
                mRecyclerView.setLayoutParams(new RecyclerView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

                // 添加分割线
                DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
                divider.setDrawable(getContext().getDrawable(R.drawable.divider_horizontal_with_margin));
                mRecyclerView.addItemDecoration(divider);
            }

            @Override
            public void onBindView(int position) {
                // 动态设置适配器（策略模式）
                if (position >= 0 && position < mAdapters.size()) {
                    mRecyclerView.setAdapter(mAdapters.get(position));
                }
            }
        }

        /**
         * 过滤数据（策略模式）
         */
        void filterData(int position, String keyword) {
            if (position >= 0 && position < getData().size()) {
                TabItem tabItem = getItem(position);
                ISubmitterProvider provider = tabItem.getProvider();
                provider.filter(keyword);
            }
        }
        
        /**
         * 收集所有Tab中选中的项（多选模式）
         * @return 用"、"分隔的所有选中项名称
         */
        String collectAllSelectedItems() {
            List<String> allSelectedItems = new ArrayList<>();
            
            // 遍历所有Adapter，收集选中的项
            for (int i = 0; i < mAdapters.size(); i++) {
                RecyclerView.Adapter<?> adapter = mAdapters.get(i);
                String selectedItems = null;
                
                // 根据不同的Adapter类型收集数据
                if (adapter instanceof TerminalAdapter) {
                    selectedItems = ((TerminalAdapter) adapter).collectSelected();
                } else if (adapter instanceof DistributorAdapter) {
                    selectedItems = ((DistributorAdapter) adapter).collectSelected();
                } else if (adapter instanceof EmployeeAdapter) {
                    selectedItems = ((EmployeeAdapter) adapter).collectSelected();
                } else if (adapter instanceof DepartmentAdapter) {
                    selectedItems = ((DepartmentAdapter) adapter).collectSelected();
                }
                
                // 如果该Tab有选中项，添加到总列表
                if (!TextUtils.isEmpty(selectedItems)) {
                    // 将"、"分隔的字符串拆分成数组，再添加到列表
                    String[] items = selectedItems.split("、");
                    for (String item : items) {
                        if (!TextUtils.isEmpty(item.trim())) {
                            allSelectedItems.add(item.trim());
                        }
                    }
                }
            }
            
            // 用"、"连接所有选中项
            return TextUtils.join("、", allSelectedItems);
        }
    }

    // ==================== 策略模式：具体 Provider 实现 ====================

    /**
     * 终端数据提供者（策略实现）
     */
    private static final class TerminalProvider implements ISubmitterProvider {
        private TerminalAdapter mAdapter;

        @Override
        public void loadData() {
            // 数据将在 Adapter 中初始化
        }

        @Override
        public void filter(String keyword) {
            if (mAdapter != null) {
                mAdapter.filter(keyword);
            }
        }

        @Override
        public RecyclerView.Adapter<?> createAdapter(Context context, Builder builder) {
            mAdapter = new TerminalAdapter(context, builder);
            return mAdapter;
        }
    }

    /**
     * 配送商数据提供者（策略实现）
     */
    private static final class DistributorProvider implements ISubmitterProvider {
        private DistributorAdapter mAdapter;

        @Override
        public void loadData() {
            // 数据将在 Adapter 中初始化
        }

        @Override
        public void filter(String keyword) {
            if (mAdapter != null) {
                mAdapter.filter(keyword);
            }
        }

        @Override
        public RecyclerView.Adapter<?> createAdapter(Context context, Builder builder) {
            mAdapter = new DistributorAdapter(context, builder);
            return mAdapter;
        }
    }

    /**
     * 业务员数据提供者（策略实现）
     */
    private static final class EmployeeProvider implements ISubmitterProvider {
        private EmployeeAdapter mAdapter;

        @Override
        public void loadData() {
            // 数据将在 Adapter 中初始化
        }

        @Override
        public void filter(String keyword) {
            if (mAdapter != null) {
                mAdapter.filter(keyword);
            }
        }

        @Override
        public RecyclerView.Adapter<?> createAdapter(Context context, Builder builder) {
            mAdapter = new EmployeeAdapter(context, builder);
            return mAdapter;
        }
    }

    /**
     * 部门数据提供者（策略实现）
     */
    private static final class DepartmentProvider implements ISubmitterProvider {
        private DepartmentAdapter mAdapter;

        @Override
        public void loadData() {
            // 数据将在 Adapter 中初始化
        }

        @Override
        public void filter(String keyword) {
            if (mAdapter != null) {
                mAdapter.filter(keyword);
            }
        }

        @Override
        public RecyclerView.Adapter<?> createAdapter(Context context, Builder builder) {
            mAdapter = new DepartmentAdapter(context, builder);
            return mAdapter;
        }
    }

    // ==================== Adapter 实现（内部使用） ====================

    /**
     * 终端适配器
     */
    private static final class TerminalAdapter extends AppAdapter<TerminalBean> {

        private final Builder mBuilder;
        private final List<TerminalBean> mAllTerminals = new ArrayList<>();

        private TerminalAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
            initTerminalData();
            setData(mAllTerminals);
        }

        private void initTerminalData() {
            mAllTerminals.add(new TerminalBean("终端名称展示在这里", "浙江省杭州市滨江区某某某科技大厦578号", "POS0000000890", true));
            mAllTerminals.add(new TerminalBean("终端名称展示在这里", "浙江省杭州市滨江区某某某科技大厦578号", "POS0000000890", true));
            mAllTerminals.add(new TerminalBean("终端名称展示在这里", "浙江省杭州市滨江区某某某科技大厦578号", "POS0000000890", false));
            mAllTerminals.add(new TerminalBean("终端名称展示在这里", "浙江省杭州市滨江区某某某科技大厦578号", "POS0000000890", false));
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder implements BaseAdapter.OnItemClickListener {

            private final CheckBox mCheckBox;
            private final TextView mNameView;
            private final TextView mAddressView;
            private final TextView mPosView;
            private final TextView mTagView;

            private ViewHolder() {
                super(R.layout.select_submitter_terminal_item);
                mCheckBox = findViewById(R.id.cb_submitter_terminal);
                mNameView = findViewById(R.id.tv_submitter_terminal_name);
                mAddressView = findViewById(R.id.tv_submitter_terminal_address);
                mPosView = findViewById(R.id.tv_submitter_terminal_pos);
                mTagView = findViewById(R.id.tv_submitter_terminal_tag);
                getItemView().setOnClickListener(v -> onItemClick(null, v, getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                TerminalBean bean = getItem(position);
                mCheckBox.setChecked(bean.isSelected());
                mNameView.setText(bean.getName());
                mAddressView.setText(bean.getAddress());
                mPosView.setText(bean.getPos());
                mTagView.setVisibility(bean.hasDebt() ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                TerminalBean selectedBean = getItem(position);

                if (mBuilder.isMultiSelect()) {
                    // 多选模式：切换选中状态
                    selectedBean.setSelected(!selectedBean.isSelected());
                    notifyItemChanged(position);
                } else {
                    // 单选模式：取消之前选中的项
                    for (TerminalBean bean : getData()) {
                        bean.setSelected(false);
                    }

                    // 设置当前选中的项
                    selectedBean.setSelected(true);
                    notifyDataSetChanged();

                    mBuilder.onSubmitterSelected(0, selectedBean.getName(), selectedBean);
                }
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项名称
         */
        String collectSelected() {
            List<String> selectedNames = new ArrayList<>();
            for (TerminalBean bean : getData()) {
                if (bean.isSelected()) {
                    selectedNames.add(bean.getName());
                }
            }
            return TextUtils.join("、", selectedNames);
        }

        void filter(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                setData(mAllTerminals);
            } else {
                List<TerminalBean> filteredList = new ArrayList<>();
                for (TerminalBean terminal : mAllTerminals) {
                    if (terminal.getName().contains(keyword) ||
                            terminal.getAddress().contains(keyword) ||
                            terminal.getPos().contains(keyword)) {
                        filteredList.add(terminal);
                    }
                }
                setData(filteredList);
            }
        }
    }

    /**
     * 配送商适配器（参考业务员实现）
     */
    private static final class DistributorAdapter extends AppAdapter<DistributorBean> {

        private final Builder mBuilder;
        private final List<DistributorBean> mAllDistributors = new ArrayList<>();

        private DistributorAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
            initDistributorData();
            setData(mAllDistributors);
        }

        private void initDistributorData() {
            mAllDistributors.add(new DistributorBean("杭州小配送1号车", "A292877"));
            mAllDistributors.add(new DistributorBean("杭州小配送2号车", "A292878"));
            mAllDistributors.add(new DistributorBean("杭州小配送3号车", "A292879"));
            mAllDistributors.add(new DistributorBean("杭州小配送4号车", "A292880"));
            mAllDistributors.add(new DistributorBean("杭州小配送5号车", "A292881"));
            mAllDistributors.add(new DistributorBean("上海配送1号车", "B100001"));
            mAllDistributors.add(new DistributorBean("上海配送2号车", "B100002"));
            mAllDistributors.add(new DistributorBean("宁波配送车辆", "C200001"));
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder implements BaseAdapter.OnItemClickListener {

            private final CheckBox mCheckBox;
            private final ImageView mAvatarView;
            private final TextView mNameView;
            private final TextView mCodeView;

            private ViewHolder() {
                super(R.layout.select_handling_person_item);
                mCheckBox = findViewById(R.id.cb_handling_person);
                mAvatarView = findViewById(R.id.iv_handling_person_avatar);
                mNameView = findViewById(R.id.tv_handling_person_name);
                mCodeView = findViewById(R.id.tv_handling_person_code);
                getItemView().setOnClickListener(v -> onItemClick(null, v, getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                DistributorBean bean = getItem(position);
                mCheckBox.setChecked(bean.isSelected());
                mNameView.setText(bean.getName());
                mCodeView.setText("车辆编码:" + bean.getCode());
                mCodeView.setVisibility(View.VISIBLE); // 显示编码
                mAvatarView.setImageResource(R.mipmap.logo_big_icon);
            }

            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DistributorBean selectedBean = getItem(position);

                if (mBuilder.isMultiSelect()) {
                    // 多选模式：切换选中状态
                    selectedBean.setSelected(!selectedBean.isSelected());
                    notifyItemChanged(position);
                } else {
                    // 单选模式：取消之前选中的项
                    for (DistributorBean bean : getData()) {
                        bean.setSelected(false);
                    }

                    // 设置当前选中的项
                    selectedBean.setSelected(true);
                    notifyDataSetChanged();

                    mBuilder.onSubmitterSelected(0, selectedBean.getName(), selectedBean);
                }
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项名称
         */
        String collectSelected() {
            List<String> selectedNames = new ArrayList<>();
            for (DistributorBean bean : getData()) {
                if (bean.isSelected()) {
                    selectedNames.add(bean.getName());
                }
            }
            return TextUtils.join("、", selectedNames);
        }

        void filter(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                setData(mAllDistributors);
            } else {
                List<DistributorBean> filteredList = new ArrayList<>();
                for (DistributorBean distributor : mAllDistributors) {
                    if (distributor.getName().contains(keyword) ||
                            distributor.getCode().contains(keyword)) {
                        filteredList.add(distributor);
                    }
                }
                setData(filteredList);
            }
        }
    }

    /**
     * 业务员适配器（类似 SelectHandlingPersonDialog）
     */
    private static final class EmployeeAdapter extends AppAdapter<EmployeeBean> {

        private final Builder mBuilder;
        private final List<EmployeeBean> mAllEmployees = new ArrayList<>();

        private EmployeeAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
            initEmployeeData();
            setData(mAllEmployees);
        }

        private void initEmployeeData() {
            mAllEmployees.add(new EmployeeBean("业务员名称"));
            mAllEmployees.add(new EmployeeBean("孙菲芸"));
            mAllEmployees.add(new EmployeeBean("吴国立"));
            mAllEmployees.add(new EmployeeBean("孙菲芸"));
            mAllEmployees.add(new EmployeeBean("吴国立"));
            mAllEmployees.add(new EmployeeBean("吴国立"));
            mAllEmployees.add(new EmployeeBean("孙菲芸"));
            mAllEmployees.add(new EmployeeBean("吴国立"));
            mAllEmployees.add(new EmployeeBean("孙菲芸"));
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder implements BaseAdapter.OnItemClickListener {

            private final CheckBox mCheckBox;
            private final ImageView mAvatarView;
            private final TextView mNameView;

            private ViewHolder() {
                super(R.layout.select_handling_person_item);
                mCheckBox = findViewById(R.id.cb_handling_person);
                mAvatarView = findViewById(R.id.iv_handling_person_avatar);
                mNameView = findViewById(R.id.tv_handling_person_name);
                findViewById(R.id.tv_handling_person_code).setVisibility(View.GONE); // 隐藏编码
                getItemView().setOnClickListener(v -> onItemClick(null, v, getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                EmployeeBean bean = getItem(position);
                mCheckBox.setChecked(bean.isSelected());
                mNameView.setText(bean.getName());
                mAvatarView.setImageResource(R.mipmap.logo_big_icon);
            }

            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                EmployeeBean selectedBean = getItem(position);

                if (mBuilder.isMultiSelect()) {
                    // 多选模式：切换选中状态
                    selectedBean.setSelected(!selectedBean.isSelected());
                    notifyItemChanged(position);
                } else {
                    // 单选模式：取消之前选中的项
                    for (EmployeeBean bean : getData()) {
                        bean.setSelected(false);
                    }

                    // 设置当前选中的项
                    selectedBean.setSelected(true);
                    notifyDataSetChanged();

                    mBuilder.onSubmitterSelected(1, selectedBean.getName(), selectedBean);
                }
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项名称
         */
        String collectSelected() {
            List<String> selectedNames = new ArrayList<>();
            for (EmployeeBean bean : getData()) {
                if (bean.isSelected()) {
                    selectedNames.add(bean.getName());
                }
            }
            return TextUtils.join("、", selectedNames);
        }

        void filter(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                setData(mAllEmployees);
            } else {
                List<EmployeeBean> filteredList = new ArrayList<>();
                for (EmployeeBean employee : mAllEmployees) {
                    if (employee.getName().contains(keyword)) {
                        filteredList.add(employee);
                    }
                }
                setData(filteredList);
            }
        }
    }

    /**
     * 部门适配器（支持展开/收起）
     */
    private static final class DepartmentAdapter extends AppAdapter<Object> {

        private static final int TYPE_COMPANY = 0;
        private static final int TYPE_DEPARTMENT = 1;
        private static final int TYPE_EMPLOYEE = 2;

        private final Builder mBuilder;
        private final List<Object> mAllItems = new ArrayList<>();
        private final List<Object> mDisplayItems = new ArrayList<>();

        private DepartmentAdapter(Context context, Builder builder) {
            super(context);
            mBuilder = builder;
            initDepartmentData();
            setData(mDisplayItems);
        }

        private void initDepartmentData() {
            // 祖名公司
            CompanyBean zuming = new CompanyBean("祖名豆制品股份有限公司");
            mAllItems.add(zuming);
            mDisplayItems.add(zuming);

            DepartmentBean dept1 = new DepartmentBean("信息部", zuming);
            mAllItems.add(dept1);
            mAllItems.add(new EmployeeBean2("孙菲芸", dept1));
            mAllItems.add(new EmployeeBean2("孙菲芸", dept1));
            mAllItems.add(new EmployeeBean2("孙菲芸", dept1));
            mAllItems.add(new EmployeeBean2("孙菲芸", dept1));

            DepartmentBean dept2 = new DepartmentBean("销管部", zuming);
            mAllItems.add(dept2);
            mAllItems.add(new EmployeeBean2("张三", dept2));
            mAllItems.add(new EmployeeBean2("李四", dept2));
            mAllItems.add(new EmployeeBean2("王五", dept2));

            DepartmentBean dept3 = new DepartmentBean("生管部", zuming);
            mAllItems.add(dept3);
            mAllItems.add(new EmployeeBean2("赵六", dept3));
            mAllItems.add(new EmployeeBean2("钱七", dept3));
            mAllItems.add(new EmployeeBean2("孙八", dept3));
            mAllItems.add(new EmployeeBean2("周九", dept3));

            DepartmentBean dept4 = new DepartmentBean("小配送部门", zuming);
            mAllItems.add(dept4);
            mAllItems.add(new EmployeeBean2("吴十", dept4));
            mAllItems.add(new EmployeeBean2("郑A", dept4));
            mAllItems.add(new EmployeeBean2("王B", dept4));

            // AAAA公司
            CompanyBean quxuan = new CompanyBean("AAAA公司");
            mAllItems.add(quxuan);
            mDisplayItems.add(quxuan);

            DepartmentBean deptA = new DepartmentBean("A部门", quxuan);
            mAllItems.add(deptA);
            mAllItems.add(new EmployeeBean2("员工A1", deptA));
            mAllItems.add(new EmployeeBean2("员工A2", deptA));
            mAllItems.add(new EmployeeBean2("员工A3", deptA));

            DepartmentBean deptB = new DepartmentBean("B部门", quxuan);
            mAllItems.add(deptB);
            mAllItems.add(new EmployeeBean2("员工B1", deptB));
            mAllItems.add(new EmployeeBean2("员工B2", deptB));
            mAllItems.add(new EmployeeBean2("员工B3", deptB));

            DepartmentBean deptC = new DepartmentBean("C部门", quxuan);
            mAllItems.add(deptC);
            mAllItems.add(new EmployeeBean2("员工C1", deptC));
            mAllItems.add(new EmployeeBean2("员工C2", deptC));
            mAllItems.add(new EmployeeBean2("员工C3", deptC));

            DepartmentBean deptD = new DepartmentBean("D部门", quxuan);
            mAllItems.add(deptD);
            mAllItems.add(new EmployeeBean2("员工D1", deptD));
            mAllItems.add(new EmployeeBean2("员工D2", deptD));
            mAllItems.add(new EmployeeBean2("员工D3", deptD));
        }

        @Override
        public int getItemViewType(int position) {
            Object item = getItem(position);
            if (item instanceof CompanyBean) {
                return TYPE_COMPANY;
            } else if (item instanceof DepartmentBean) {
                return TYPE_DEPARTMENT;
            } else {
                return TYPE_EMPLOYEE;
            }
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            switch (viewType) {
                case TYPE_COMPANY:
                    return new CompanyViewHolder();
                case TYPE_DEPARTMENT:
                    return new DepartmentViewHolder();
                case TYPE_EMPLOYEE:
                default:
                    return new EmployeeViewHolder();
            }
        }

        private final class CompanyViewHolder extends AppAdapter<?>.ViewHolder {
            private final ImageView mArrowView;
            private final TextView mNameView;

            private CompanyViewHolder() {
                super(R.layout.select_submitter_company_item);
                mArrowView = findViewById(R.id.iv_company_arrow);
                mNameView = findViewById(R.id.tv_company_name);
                getItemView().setOnClickListener(v -> toggleCompany(getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                CompanyBean bean = (CompanyBean) getItem(position);
                mNameView.setText(bean.getName());
                mArrowView.setImageResource(bean.isExpanded() ? R.drawable.arrow_shang : R.drawable.arrow_xia);
            }

            private void toggleCompany(int position) {
                CompanyBean company = (CompanyBean) getItem(position);
                company.setExpanded(!company.isExpanded());

                if (company.isExpanded()) {
                    // 展开：在当前公司后面插入该公司的所有部门
                    List<Object> departments = new ArrayList<>();
                    for (Object item : mAllItems) {
                        if (item instanceof DepartmentBean && ((DepartmentBean) item).getCompany() == company) {
                            departments.add(item);
                        }
                    }
                    mDisplayItems.addAll(position + 1, departments);
                } else {
                    // 收起：移除该公司下的所有部门和员工
                    List<Object> toRemove = new ArrayList<>();
                    for (int i = position + 1; i < mDisplayItems.size(); i++) {
                        Object item = mDisplayItems.get(i);
                        if (item instanceof DepartmentBean) {
                            DepartmentBean dept = (DepartmentBean) item;
                            if (dept.getCompany() == company) {
                                dept.setExpanded(false); // 收起部门
                                toRemove.add(item);
                            } else {
                                break; // 遇到其他公司的部门，停止
                            }
                        } else if (item instanceof EmployeeBean2) {
                            EmployeeBean2 emp = (EmployeeBean2) item;
                            if (emp.getDepartment().getCompany() == company) {
                                toRemove.add(item);
                            } else {
                                break;
                            }
                        } else {
                            break; // 遇到下一个公司，停止
                        }
                    }
                    mDisplayItems.removeAll(toRemove);
                }

                setData(mDisplayItems);
            }
        }

        private final class DepartmentViewHolder extends AppAdapter<?>.ViewHolder {
            private final ImageView mArrowView;
            private final TextView mNameView;

            private DepartmentViewHolder() {
                super(R.layout.select_submitter_department_item);
                mArrowView = findViewById(R.id.iv_department_arrow);
                mNameView = findViewById(R.id.tv_department_name);
                getItemView().setOnClickListener(v -> toggleDepartment(getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                DepartmentBean bean = (DepartmentBean) getItem(position);
                mNameView.setText(bean.getName());
                mArrowView.setImageResource(bean.isExpanded() ? R.drawable.arrow_shang : R.drawable.arrow_xia);
            }

            private void toggleDepartment(int position) {
                DepartmentBean dept = (DepartmentBean) getItem(position);
                dept.setExpanded(!dept.isExpanded());

                if (dept.isExpanded()) {
                    // 展开：在当前部门后面插入员工
                    List<Object> employees = new ArrayList<>();
                    for (Object item : mAllItems) {
                        if (item instanceof EmployeeBean2 && ((EmployeeBean2) item).getDepartment() == dept) {
                            employees.add(item);
                        }
                    }
                    mDisplayItems.addAll(position + 1, employees);
                } else {
                    // 收起：移除该部门下的所有员工
                    List<Object> toRemove = new ArrayList<>();
                    for (int i = position + 1; i < mDisplayItems.size(); i++) {
                        Object item = mDisplayItems.get(i);
                        if (item instanceof EmployeeBean2 && ((EmployeeBean2) item).getDepartment() == dept) {
                            toRemove.add(item);
                        } else if (!(item instanceof EmployeeBean2)) {
                            break;
                        }
                    }
                    mDisplayItems.removeAll(toRemove);
                }

                setData(mDisplayItems);
            }
        }

        private final class EmployeeViewHolder extends AppAdapter<?>.ViewHolder {
            private final CheckBox mCheckBox;
            private final ImageView mAvatarView;
            private final TextView mNameView;

            private EmployeeViewHolder() {
                super(R.layout.select_submitter_employee_item);
                mCheckBox = findViewById(R.id.cb_employee);
                mAvatarView = findViewById(R.id.iv_employee_avatar);
                mNameView = findViewById(R.id.tv_employee_name);
                getItemView().setOnClickListener(v -> onItemClick(getViewHolderPosition()));
            }

            @Override
            public void onBindView(int position) {
                EmployeeBean2 bean = (EmployeeBean2) getItem(position);
                mCheckBox.setChecked(bean.isSelected());
                mNameView.setText(bean.getName());
                mAvatarView.setImageResource(R.mipmap.logo_big_icon);
            }

            private void onItemClick(int position) {
                EmployeeBean2 selectedBean = (EmployeeBean2) getItem(position);

                if (mBuilder.isMultiSelect()) {
                    // 多选模式：切换选中状态
                    selectedBean.setSelected(!selectedBean.isSelected());
                    notifyItemChanged(position);
                } else {
                    // 单选模式：取消之前选中的项
                    for (Object item : mDisplayItems) {
                        if (item instanceof EmployeeBean2) {
                            ((EmployeeBean2) item).setSelected(false);
                        }
                    }

                    // 设置当前选中的项
                    selectedBean.setSelected(true);
                    notifyDataSetChanged();

                    mBuilder.onSubmitterSelected(2, selectedBean.getName(), selectedBean);
                }
            }
        }
        
        /**
         * 收集选中的项（多选模式）
         * @return 用"、"分隔的选中项名称
         */
        String collectSelected() {
            List<String> selectedNames = new ArrayList<>();
            // 从所有数据中收集选中的员工
            for (Object item : mAllItems) {
                if (item instanceof EmployeeBean2) {
                    EmployeeBean2 emp = (EmployeeBean2) item;
                    if (emp.isSelected()) {
                        selectedNames.add(emp.getName());
                    }
                }
            }
            return TextUtils.join("、", selectedNames);
        }

        void filter(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                // 恢复原始状态（只显示公司）
                mDisplayItems.clear();
                for (Object item : mAllItems) {
                    if (item instanceof CompanyBean) {
                        mDisplayItems.add(item);
                    } else if (item instanceof DepartmentBean) {
                        ((DepartmentBean) item).setExpanded(false);
                    }
                }
                setData(mDisplayItems);
            } else {
                // 搜索：展示匹配的员工
                List<Object> filteredList = new ArrayList<>();
                for (Object item : mAllItems) {
                    if (item instanceof EmployeeBean2) {
                        EmployeeBean2 emp = (EmployeeBean2) item;
                        if (emp.getName().contains(keyword)) {
                            filteredList.add(emp);
                        }
                    }
                }
                mDisplayItems.clear();
                mDisplayItems.addAll(filteredList);
                setData(mDisplayItems);
            }
        }
    }

    /**
     * 终端数据Bean
     */
    private static class TerminalBean {
        private String name;
        private String address;
        private String pos;
        private boolean hasDebt;
        private boolean selected;

        public TerminalBean(String name, String address, String pos, boolean hasDebt) {
            this.name = name;
            this.address = address;
            this.pos = pos;
            this.hasDebt = hasDebt;
            this.selected = false;
        }

        public String getName() {
            return name;
        }

        public String getAddress() {
            return address;
        }

        public String getPos() {
            return pos;
        }

        public boolean hasDebt() {
            return hasDebt;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 配送商数据Bean
     */
    private static class DistributorBean {
        private String name;
        private String code; // 车辆编码
        private boolean selected;

        public DistributorBean(String name, String code) {
            this.name = name;
            this.code = code;
            this.selected = false;
        }

        public String getName() {
            return name;
        }

        public String getCode() {
            return code;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 业务员数据Bean
     */
    private static class EmployeeBean {
        private String name;
        private boolean selected;

        public EmployeeBean(String name) {
            this.name = name;
            this.selected = false;
        }

        public String getName() {
            return name;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 公司数据Bean
     */
    private static class CompanyBean {
        private String name;
        private boolean expanded;

        public CompanyBean(String name) {
            this.name = name;
            this.expanded = false;
        }

        public String getName() {
            return name;
        }

        public boolean isExpanded() {
            return expanded;
        }

        public void setExpanded(boolean expanded) {
            this.expanded = expanded;
        }
    }

    /**
     * 部门数据Bean
     */
    private static class DepartmentBean {
        private String name;
        private CompanyBean company;
        private boolean expanded;

        public DepartmentBean(String name, CompanyBean company) {
            this.name = name;
            this.company = company;
            this.expanded = false;
        }

        public String getName() {
            return name;
        }

        public CompanyBean getCompany() {
            return company;
        }

        public boolean isExpanded() {
            return expanded;
        }

        public void setExpanded(boolean expanded) {
            this.expanded = expanded;
        }
    }

    /**
     * 员工数据Bean（部门页面用）
     */
    private static class EmployeeBean2 {
        private String name;
        private DepartmentBean department;
        private boolean selected;

        public EmployeeBean2(String name, DepartmentBean department) {
            this.name = name;
            this.department = department;
            this.selected = false;
        }

        public String getName() {
            return name;
        }

        public DepartmentBean getDepartment() {
            return department;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 选择监听器
     */
    public interface OnListener {

        /**
         * 选择提交人
         *
         * @param dialog     对话框对象
         * @param submitter  选中的提交人名称
         * @param type       Tab索引（根据不同的 Dialog type，含义不同）
         * @param data       选中的完整数据对象（TerminalBean/DistributorBean/EmployeeBean/EmployeeBean2）
         */
        void onSelected(BaseDialog dialog, String submitter, int type, Object data);

        /**
         * 取消选择
         */
        default void onCancel(BaseDialog dialog) {
        }
    }
}
